package com.biubiux2.dao;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Lijinbao
 * @since 8/5/2022 11:59 AM
 */
@Slf4j
public class DaoUtil {

    public static final SqlSession SQL_SESSION;

    public static final ConcurrentHashMap<Class<?>, Object> MAPPER_MAP = new ConcurrentHashMap<>();

    static {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            log.debug("mybatis 初始化失败！");
            throw new RuntimeException(e);
        }
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SQL_SESSION = sessionFactory.openSession(true);
    }

    public static <T> T getMapper(Class<T> clazz) {
        Object mapper = MAPPER_MAP.get(clazz);
        if (mapper == null) {
            mapper = SQL_SESSION.getMapper(clazz);
            MAPPER_MAP.put(clazz, mapper);
        }
        return (T) mapper;
    }

}
